var util = require("util");
var fs = require("fs");
var path = require("path");
var helper = require("./helper.js");
var logger = helper.getLogger("Create-Channel");

//Attempt to send a request to the orderer with the sendCreateChain method
var createChannel = function(
  channelName,
  channelConfigPath,
  username,
  orgName
) {
  logger.debug("\n====== Creating Channel '" + channelName + "' ======\n");
  var client = helper.getClientForOrg(orgName);
  var channel = helper.getChannelForOrg(orgName);

  // read in the envelope for the channel config raw bytes
  var envelope = fs.readFileSync(path.join(__dirname, channelConfigPath));
  // extract the channel config bytes from the envelope to be signed
  var channelConfig = client.extractChannelConfig(envelope);

  //Acting as a client in the given organization provided with "orgName" param
  return helper
    .getOrgAdmin(orgName)
    .then(
      admin => {
        logger.debug(
          util.format(
            'Successfully acquired admin user for the organization "%s"',
            orgName
          )
        );
        // sign the channel config bytes as "endorsement", this is required by
        // the orderer's channel creation policy
        let signature = client.signChannelConfig(channelConfig);

        let request = {
          config: channelConfig,
          signatures: [signature],
          name: channelName,
          orderer: channel.getOrderers()[0],
          txId: client.newTransactionID()
        };

        // send to orderer
        return client.createChannel(request);
      },
      err => {
        logger.error("Failed to enroll user '" + username + "'. Error: " + err);
        throw new Error("Failed to enroll user '" + username + "'" + err);
      }
    )
    .then(
      response => {
        logger.debug(" response ::%j", response);
        if (response && response.status === "SUCCESS") {
          logger.debug("Successfully created the channel.");
          let response = {
            success: true,
            message: "Channel '" + channelName + "' created Successfully"
          };
          return response;
        } else {
          logger.error(
            "\n!!!!!!!!! Failed to create the channel '" +
              channelName +
              "' !!!!!!!!!\n\n"
          );
          throw new Error("Failed to create the channel '" + channelName + "'");
        }
      },
      err => {
        logger.error(
          "Failed to initialize the channel: " + err.stack ? err.stack : err
        );
        throw new Error(
          "Failed to initialize the channel: " + err.stack ? err.stack : err
        );
      }
    );
};

exports.createChannel = createChannel;
